# @Time    : 2021/9/26 3:00
# @Author  : tzhhone
# @File    : data_output.py
# @Explain : 数据存储器
import os
import pymysql
import yaml

from tzhhone_reptile.log import Log

yaml_path = os.path.join(os.getcwd(), "config.yaml")
file = open(yaml_path, 'r', encoding='utf-8')
dataMysql = yaml.load(file, Loader=yaml.FullLoader)["mysql"]
file.close()


class DataOutput(Log):
    def __init__(self, token):
        self.db = pymysql.connect(host=dataMysql["host"], port=dataMysql["port"], user=dataMysql["user"],
                                  password=dataMysql["password"], database=dataMysql["database"])
        self.cursor = self.db.cursor()
        self.token = token
        self.last_id = 0

    def __del__(self):
        self.db.close()
        self.cursor.close()

    def get_bsc_info_exist(self):
        """
        判断币种是否存在
        :return:
        """
        sql = "SELECT * FROM bsc_info WHERE contract='%s';" % self.token
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res

    def set_info(self, info):
        """
        写入币种基础信息
        :param info: 币种信息  BscInfo
        :return:
        """
        res = self.get_bsc_info_exist()
        if res is None:
            sql = "INSERT INTO `bsc_bit`.`bsc_info`(`name`, `holders`, `contract`, `official_site`, `total_supply`, " \
                  "`transfers`, `decimals`, `price`) VALUES ('%s',%s, '%s', '%s', %s, %s, %s, %s); " \
                  % (str(info.name), str(info.holders), str(info.contract), str(info.official_site),
                     str(info.total_supply),
                     str(info.transfers), str(info.decimals), str(info.price))
            try:
                # 执行sql语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()
                # 获取id
                self.last_id = self.cursor.lastrowid
            except Exception as var:
                DataOutput.logger.error("新增币种出错。\n错误原因:" + var.args)
                # 如果发生错误则回滚
                self.db.rollback()
        else:
            sql = "UPDATE `bsc_bit`.`bsc_info` SET `name` = '%s', `holders` = %s, `official_site` = '%s', " \
                  "`total_supply` = '%s', `transfers` = %s, `decimals` = %s, `price` = %s WHERE `contract` = '%s'; " \
                  % (
                      str(info.name), str(info.holders), str(info.official_site), str(info.total_supply),
                      str(info.transfers), str(info.decimals), str(info.price), self.token)
            try:
                # 执行sql语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()
                # 获取id
                self.last_id = res[0]

            except Exception as var:
                DataOutput.logger.error("更新币种信息出错。\n错误原因:" + var.args)
                # 如果发生错误则回滚
                self.db.rollback()

    def set_update_info(self, info):
        """
        写入币种按时间更新
        :param info: 币种信息  BscInfo
        :return:
        """
        if self.last_id != 0:
            sql = "INSERT INTO `bsc_bit`.`bsc_info_time`(`i_id`, `name`, `holders`, `transfers`, `price`) VALUES (%s, " \
                  "'%s', %s, %s, %s);" % (str(self.last_id), str(info.name), str(info.holders), str(info.transfers),
                                          str(info.price))
            try:
                # 执行sql语句
                self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()

            except Exception as var:
                DataOutput.logger.error("err:添加info_time信息出错。\n错误原因：" + var.args)
                # 如果发生错误则回滚
                self.db.rollback()
        else:
            DataOutput.logger.warning("err:last_id为0")

    def set_rank(self, rank_info):
        """
        写入币种排名信息
        :param rank_info: 币种排名信息 List[BscCoins]
        :return:
        """
        if rank_info is not None:
            try:
                for item in rank_info:
                    sql = "INSERT INTO `bsc_bit`.`bsc_address_info`(`i_id`, `rank`, `address`, `coins`, `url`) VALUES (%s, " \
                          "%s, '%s', %s,'%s');" \
                          % (str(self.last_id), str(item.rank), str(item.address), str(item.coins), str(item.url))
                    # 执行sql语句
                    self.cursor.execute(sql)
                # 提交到数据库执行
                self.db.commit()

            except Exception as var:
                DataOutput.logger.error("err:写入币种前50名信息出错。\n错误原因：%s" % var.args)
                # 如果发生错误则回滚
                self.db.rollback()
